import React, { useState, useEffect } from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { ColumnsType } from 'antd/es/table';
import { Card, Table, Button, Tabs, Modal, Alert, Space, Upload, message } from 'antd';
import { connect, FormattedMessage, useIntl } from 'umi';
import { ImportOutlined, ExportOutlined } from '@ant-design/icons';
import { momentStr } from '@/utils/utils';
import SearchForm from './SearchForm';
import UpdateVendor from './UpdateVendor';
import request from '@/utils/request';
import UploadUtil from '@/components/UploadUtil';
import QuickMenu from '@/components/QuickMenu';

//columns
interface User {
  key: number;
  partNum: string;
  partDescription: any;
  opCode: string;
  pum: string;
  baseUnitPrice: string;
  effectiveDate: string;
  expirationDate: string;
}
const { TabPane } = Tabs;
const apiURL = '/api/services/app/VendPart/';

const ViewPage: React.FC<any> = (props) => {
  const [visible, setVisible] = useState(false);
  const [formVals, setFormVals] = useState({});
  const [editStatus, setEditStatus] = useState(false);
  const [defaultParams, setDefaultParams] = useState({});
  const [params, setParams] = useState({
    skipCount: 0,
    maxResultCount: 999999,
  });
  const [hideOpcode, setHideOpcode] = useState(false);
  const [dataOutSource, setDataOutSource] = useState<any[]>([]);
  const [dataOpCode, setDataOpCode] = useState<any[]>([]);
  const [loading, setLoading] = useState(false);
  const [totalCount, setTotalCount] = useState(0);
  const [totalCount2, setTotalCount2] = useState(0);
  const [eType, setEType] = useState('MTL');
  const intl = useIntl();
  useEffect(() => {
    fetchData();
  }, [params]);

  const fetchData = () => {
    const tempOpCode: any[] = [];
    const tempOutSource: any[] = [];
    setLoading(true);
    request(apiURL + 'GetList', {
      method: 'GET',
      params: { ...params },
    }).then((response) => {
      if (response) {
        if (response && response.result?.items) {
          response.result.items.forEach((item: any) => {
            if (item.pricePerCode == 'SUB') {
              tempOpCode.push(item);
            } else {
              tempOutSource.push(item);
            }
          });
          setDataOutSource(tempOutSource);
          setDataOpCode(tempOpCode);
          setTotalCount(tempOutSource.length);
          setTotalCount2(tempOpCode.length);
        }
        setLoading(false);
      }
    });
  };

  const handleSearch = (values: any) => {
    setParams({
      ...values,
      skipCount: 0,
      maxResultCount: 999999,
    });
  };

  const handleSubmit = async (values: any) => {
    const { dispatch } = props;
    if (editStatus) {
      await dispatch({
        type: 'Abp/update',
        payload: { ...values },
        control: 'VendPart',
      });
    } else {
      await dispatch({
        type: 'Abp/create',
        payload: { ...values },
        control: 'VendPart',
      });
    }
    switchVisible();
    fetchData();
  };

  const switchVisible = (visible = false, formVals = {}, editStatus = false) => {
    setVisible(visible);
    setFormVals(formVals);
    setEditStatus(editStatus);
  };

  const handlerExport = async () => {
    setLoading(true);
    var resp = await request('/api/Excel/ExportVendorPart', {
      method: 'POST',
      responseType: 'blob',
    });

    var url = window.URL.createObjectURL(resp);
    var a = document.createElement('a');
    a.href = url;
    a.download = 'VendorPart.xls';
    a.click();
    setLoading(false);
  };

  const handlerImport = (info: any) => {
    if (info.file.status === 'done') {
      message.success(intl.formatMessage({id:'pages.import.success'}));
      setLoading(false);
      fetchData();
    } else {
      setLoading(true);
    }
  };

  const columnsOut: ColumnsType<User> = [
    {
      title: <FormattedMessage id="pages.partNum" />,
      dataIndex: 'partNum',
      align: 'center',
      width: 100,
    },
    {
      title: <FormattedMessage id="pages.partDescription" />,
      dataIndex: 'partDescription',
      align: 'center',
      width: 150,
      ellipsis: true,
    },
    {
      title: <FormattedMessage id="pages.baseUnitPrice" />,
      dataIndex: 'baseUnitPrice',
      align: 'center',
      width: 100,
    },
    {
      title: <FormattedMessage id="pages.IUM" />,
      dataIndex: 'pum',
      align: 'center',
      width: 100,
    },
    {
      title: <FormattedMessage id="pages.effectiveDate" />,
      dataIndex: 'effectiveDate',
      align: 'center',
      render: (val: any) => momentStr(val),
      width: 120,
    },
    {
      title: <FormattedMessage id="pages.expirationDate" />,
      dataIndex: 'expirationDate',
      align: 'center',
      render: (val: any) => momentStr(val),
      width: 120,
    },
  ];

  const columnsOpCode: ColumnsType<User> = [
    {
      title: <FormattedMessage id="pages.partNum" />,
      dataIndex: 'partNum',
      align: 'center',
      width: 100,
    },
    {
      title: <FormattedMessage id="pages.partDescription" />,
      dataIndex: 'partDescription',
      align: 'center',
      width: 180,
      ellipsis: true,
    },
    {
      title: <FormattedMessage id="pages.opCode" />,
      dataIndex: 'opCode',
      align: 'center',
      width: 120,
    },
    {
      title: <FormattedMessage id="pages.baseUnitPrice" />,
      dataIndex: 'baseUnitPrice',
      align: 'center',
      width: 100,
    },
    {
      title: <FormattedMessage id="pages.IUM" />,
      dataIndex: 'pum',
      align: 'center',
      width: 100,
    },
    {
      title: <FormattedMessage id="pages.effectiveDate" />,
      dataIndex: 'effectiveDate',
      align: 'center',
      render: (val: any) => momentStr(val),
      width: 120,
    },
    {
      title: <FormattedMessage id="pages.expirationDate" />,
      dataIndex: 'expirationDate',
      align: 'center',
      render: (val: any) => momentStr(val),
      width: 120,
    },
  ];

  return (
    <PageHeaderWrapper title={false} breadcrumbRender={false} ghost>
      <Card extra={[
        <SearchForm onSearch={handleSearch} defaultParams={defaultParams}>
          <Space>
            <Button type="primary" onClick={() => switchVisible(true)}>
              <FormattedMessage id="pages.new" />
            </Button>
            <Button
              icon={<ExportOutlined />}
              type="dashed"
              onClick={() => handlerExport()}
              loading={loading}
            >
              <span>
                <FormattedMessage id="pages.export" />
              </span>
            </Button>
            <Upload
              accept=".xls,.xlsx,application/vnd.ms-excel"
              name="file"
              action="/api/Excel/ImportVendorPart"
              headers={{
                Authorization: UploadUtil.accessToken,
              }}
              beforeUpload={UploadUtil.checkExcel}
              showUploadList={false}
              onChange={handlerImport}
            >
              <Button icon={<ImportOutlined />} type="dashed" loading={loading}>
                <span>
                  <FormattedMessage id="pages.import" />
                </span>
              </Button>
            </Upload>
            <QuickMenu path="/purchase/vendorPrice" icon="icon-document" title="pages.VendorPrice" />
          </Space>
        </SearchForm>
      ]}>
        <Tabs defaultActiveKey="1" onChange={(e: any) => setEType(e)} tabPosition={'left'}>
          <TabPane tab={<FormattedMessage id="pages.purchase.quote" />} key="MTL">
            <Table
              rowKey="id"
              scroll={{ x: '1800' }}
              size="small"
              columns={columnsOut}
              dataSource={dataOutSource}
              loading={loading}
              onRow={(record) => {
                return {
                  onDoubleClick: (event) => {
                    switchVisible(true, record, true);
                  },
                };
              }}
              pagination={{
                pageSize: 10,
                total: totalCount,
              }}
            />
          </TabPane>
          <TabPane tab={<FormattedMessage id="pages.oper.quote" />} key="SUB">
            <Table
              rowKey="id"
              scroll={{ x: '1800' }}
              size="small"
              columns={columnsOpCode}
              dataSource={dataOpCode}
              loading={loading}
              onRow={(record) => {
                return {
                  onDoubleClick: (event) => {
                    switchVisible(true, record, true);
                  },
                };
              }}
              pagination={{
                pageSize: 10,
                total: totalCount2,
              }}
            />
          </TabPane>
        </Tabs>
        <Alert
          message={intl.formatMessage({id:'pages.vendorPriceEditTips'})}
          type="warning"
          showIcon
          closable
        />
      </Card>
      <Modal
        title={
          editStatus ? <FormattedMessage id="pages.quote.edit" /> : <FormattedMessage id="pages.quote.create" />
        }
        width="640px"
        bodyStyle={{ padding: 24 }}
        visible={visible}
        destroyOnClose
        footer={null}
        onCancel={() => setVisible(false)}
      >
        <UpdateVendor
          hideOpcode={hideOpcode}
          formVals={formVals}
          eType={eType}
          onSubmit={handleSubmit}
        />
      </Modal>
    </PageHeaderWrapper>
  );
};

export default connect(({ Abp }: API.IConnectState) => ({
  response: Abp.response,
  currentUser: Abp.currentUser,
}))(ViewPage);
